#ifndef __MF1CardWork_C
#define __MF1CardWork_C

#include "MF1CardWork.h"

// 刷卡初始化：开启天线
void RC522_init(){
		PcdReset();  
		PcdAntennaOff();  
		M500PcdConfigISOType('A');  
	  // 刷卡准备妥当
	  RC522_ready = 1;
}

// 刷卡检测任务开启：
void card_task_read_start(){
	  // 启动刷卡检测:
	  card_step = 1;	  	 
    RC522_init(); 
    card_data_readAndParse();
	
		//printf(" card_task_read_start  %d  \r\n ",card_step);	
		PcdHalt();
}

// 读卡前奏
int8_t card_step_prelude(){
	  int8_t status = 0;
		int8_t i = 0;
	  if(card_step > 0){			  
        // 寻卡			
			  status = PcdRequest(PICC_REQALL, g_ucTempbuf); 
				if(status == MI_OK){						
						for(i = 0; i < 2; i++){
								m1CardInfo[i] = g_ucTempbuf[i];  
						}
            card_step = 2;
				} else {
					  card_step = -2;
					  return card_step;
				}
				// 防碰撞
				status = PcdAnticoll(g_ucTempbuf); 
				if(status == MI_OK){ 
						for(i = 0; i < 4; i++){
								m1CardInfo[i+2] = g_ucTempbuf[i]; 
						}
						card_step = 3; 						
				}	else {
					  card_step = -3; 
					  return card_step;
				}	 
				// 选卡
				status = PcdSelect(g_ucTempbuf);  
        if(status == MI_OK){
						card_step = 4;            						
				}	else {
					  card_step = -4;
            return card_step;					
				}		
		}
		return card_step;	
}

//// 判断是否是新卡
//int8_t card_step_isNewCard(){
//		int8_t status = 0;
//	  card_step = card_step_prelude();
//	  if(card_step > 3){
//			  // 新卡检测，新卡密码检验
//				unsigned char passwdFirst[6] = {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF};
//				// 密码验证：
//				status = PcdAuthState(PICC_AUTHENT1A,cardOper_blockId,passwdFirst,g_ucTempbuf);  
//				if(status == MI_OK){
//						// 新卡验证成功
//						card_type = card_state_new;
//						// 新卡就直接进行设置密码;或不操作
//						card_step = 5;
//				} else {
//					  card_step = -5;
//            return card_step;		
//				}
//		}
//		return card_step;	
//}

// 读就卡数据，并解析数据
int8_t card_data_readAndParse(){
	  int8_t status = 0;
    int8_t i = 0;		  
		unsigned char passwd[6];
    card_step = card_step_prelude();	
	  if(card_step > 3){			  
				// 准备密码：
			  for(i = 0; i < 6; i++){
					  passwd[i] = card_pwd[i];
				}
				encryptStr(passwd,m1CardInfo,6);
			  // 密码验证：
			  status = PcdAuthState(PICC_AUTHENT1A,cardOper_blockId,passwd,g_ucTempbuf);  
				if(status == MI_OK){
					  card_type = card_state_charge;
					  card_step = 6;
				}else{
						card_step = -6;
					  return card_step;	
				}			
				// 读数据：
			  status = PcdRead(cardOper_blockId,g_ucTempbuf);  
				if(status == MI_OK){					
						//读取卡内数据成功：打印数据;
						#ifdef SYS_DEBUG
								printf(" g_ucTempbuf =  ");
								for(i = 0; i < 16; i++){
									  printf("0x%02x ",g_ucTempbuf[i]);
								} 
								printf("\r\n");	
						#endif //PCB_Debug
            parseCardData();
						card_step = 7; 
				}	else {
					  card_step = -7;
				}
				#ifdef SYS_DEBUG
				printf(" card_step_run =  0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x \r\n",g_ucTempbuf[0],g_ucTempbuf[1],g_ucTempbuf[2],g_ucTempbuf[3],g_ucTempbuf[4],g_ucTempbuf[5]);				
				printf(" card_step_run =  0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x \r\n",m1CardInfo[0],m1CardInfo[1],m1CardInfo[2],m1CardInfo[3],m1CardInfo[4],m1CardInfo[5]);	
				printf(" card_step_run =  %d \r\n",card_step);		
				#endif //PCB_Debug
		}
		return card_step;	
}

////将密码写进卡里:必须先执行card_step_isNewCard
//int8_t card_write_pwd(){
//	  uint8_t status;
//	  uint8_t i = 0;
//	  unsigned char passwd[6] = cardPwd;
//    unsigned char passwdB[6] = cardPwdB;  
//		unsigned char data1[16];
//		unsigned char contrlMode[4] = PWDContrlMode;
//		if(card_step > 4){
//			  encryptStr(passwd,m1CardInfo,6);  
//		    encryptStr(passwdB,m1CardInfo,6);  
//			  for(i = 0;i < 6;i++){
//						data1[i] = passwd[i];
//						data1[i+10] = passwdB[i];
//				} 
//				for(i = 0;i < 4;i++){
//						data1[i+6] = contrlMode[i];    
//				}
//				// 计算密码块id = i：扇区号 = cardOper_blockId / 4取整
//				i = (uint8_t)(cardOper_blockId / 4) + 3; 
//				status = PcdWrite(i,data1); 
//				if(status == MI_OK){ 
//					  card_type = card_state_charge; 
//						card_step = 8;
//						return card_step;
//				}else{
//						card_step = -8;
//				} 	
//		}
//		return card_step; 
//}

// 将数据写入到卡中：riteData = 16字节数组; 
int8_t card_write_data(unsigned char *riteData){
		unsigned char status;
		unsigned char passwd[6];
	  card_step_prelude();
    if(card_step > 3){
			  uint8_t i = 0;
				// 准备密码：
			  for(i = 0; i < 6; i++){
					  passwd[i] = card_pwd[i];
				}
				encryptStr(passwd,m1CardInfo,6);
			  // 密码验证：
			  status = PcdAuthState(PICC_AUTHENT1A,cardOper_blockId,passwd,g_ucTempbuf);  
				if(status == MI_OK){
					  card_type = card_state_charge;
					  card_step = 9;
				}else{
						card_step = -9;
					  return card_step;	
				}
        // 写数据：
        status = PcdWrite(cardOper_blockId,riteData);	
        if(status == MI_OK){
						card_step = 10;
					  #if beep_type > 0 && (Using_UART_LCD == LCD_4P3_UART || beep_type == beep_APM || beep_type == beep_BPM)
						// 读卡后，提示音
						beep_start(2,200,200);
						#endif
						return card_step;
				}else{
						card_step = -10;
				} 						
		}	
		#ifdef SYS_DEBUG
		printf(" card_write_data =  %d \r\n",card_step);		
		#endif //PCB_Debug
		return card_step; 
}

//// 更新密码： 
//int8_t card_update_PWD(unsigned char *oldPwd,unsigned char *newPwd){
//		unsigned char status, i = 0;
//	  unsigned char data1[16];
//		unsigned char passwd[6]; 
//	  unsigned char passwdB[6] = cardPwdB; //密码B保持默认;
//	  unsigned char contrlMode[4] = PWDContrlMode;
//	  card_step = 1;
//    for(i = 0; i < 6; i++){
//			  passwd[i] = oldPwd[i];
//		}	
//	  card_step = card_step_prelude();
//    if(card_step > 3){
//				// 准备密码：
//				encryptStr(passwd,m1CardInfo,6);
//			  // 密码验证：
//			  status = PcdAuthState(PICC_AUTHENT1A,cardOper_blockId,passwd,g_ucTempbuf);  
//				if(status == MI_OK){
//					  card_type = card_state_charge;
//					  card_step = 9;
//				}else{
//						card_step = -9;
//					  return card_step;	
//				}
//				// 准备新密码：
//				encryptStr(passwd,m1CardInfo,6); 
//		    encryptStr(passwdB,m1CardInfo,6); 
//			  for(i = 0;i < 6;i++){
//						data1[i] = passwd[i];
//						data1[i+10] = passwdB[i];
//				} 
//				for(i = 0;i < 4;i++){
//						data1[i+6] = contrlMode[i];    
//				}
//				// 计算密码块id = i：扇区号 = cardOper_blockId / 4取整
//				i = (uint8_t)(cardOper_blockId / 4) + 3; 
//				status = PcdWrite(i,data1); 
//        if(status == MI_OK){
//						card_step = 11;
//					  #if beep_type > 0
//						// 读卡后，提示音
//						beep_start(3,100,200);
//						#endif
//						return card_step;
//				}else{
//						card_step = -11;
//				} 						
//		}	
//		return card_step;  
//}

// 将金额写入到卡中：单位 = 分
int8_t card_write_cash(long writeCash){
		char i;
		unsigned char data1[16];
    unsigned char passwdCash[6] = CASH_PWD;	
		unsigned char cashTips[4] = CASH_TIP; 
    card_step = 1;	
		// 	金额数据字节准备	
		for(i=0;i<4;i++){
				data1[i] = (unsigned char)((writeCash >> (8*i)) & 0x000000ff);    
		} 
    // 数据字节加密		
		encryptStr(data1,passwdCash,4); 
    // 加密数据互补位		
		for(i=0;i<4;i++){    
			data1[i+4] = ~data1[i];        
		}  
		// 金额数据提示文本加密
		encryptStr(cashTips,passwdCash,4);  
		for(i=0;i<4;i++){    
			data1[i+8] = cashTips[i];        
		}  
		// 数据属性标志位：
		data1[12] = cardDataTypeCash0;
		data1[13] = cardDataTypeCash1;
		data1[14] = cardDataTypeCash2;
		data1[15] = cardDataTypeCash3;
		// 保存金额数据	
		card_step = card_write_data(data1);		
		return card_step;  
}

//// 将免费卡数据写入到卡中：共8位会员数据;
//int8_t card_write_freeMem(char *menberId){
//		char i;
//		unsigned char data1[16];
//	  card_step = 1;
//		// 	会员数据准备	
//		for(i = 0; i < 8; i++){
//			data1[i] = menberId[i];
//		} 
//    //互补验证位：	
//		for(i = 0; i < 4; i++){    
//			data1[i + 8] = ~data1[i];        
//		}  
//		// 数据属性标志位：
//		data1[12] = cardDataTypeFree0;
//		data1[13] = cardDataTypeFree1;
//		data1[14] = cardDataTypeFree2;
//		data1[15] = cardDataTypeFree3;
//		// 保存金额数据	
//		card_write_data(data1);		
//		return card_step;  
//}


// 设置充电参数设置卡数据:
// chgPrice = 刷一次卡扣除的钱;单位=分。100分 = 1元。
// chgTime  = 一次刷卡可以充电的时间：单位 = 2分钟。
// chgPowNormal  = 一次刷卡充电的正常功率, 按时计费时，需要用到。超功率，需要缩短充电时长。单位 = 100W。
// chgEnergy  = 若按时计费，chgTime > 0时，此设为0。一次刷卡充电的电量。单位 = 0.1度电。
//int8_t card_write_chgCtrlSets(uint16_t chgPrice,uint16_t chgTime,uint16_t chgPowNormal,uint16_t chgEnergy){
//		char i;
//		unsigned char data1[16];
//		// 	充电数据准备	
//		for(i = 0;i < 2;i++){
//				data1[i] = (unsigned char)((chgPrice >> (8 * i)) & 0x00ff);    
//		}
//		for(i = 2;i < 4;i++){
//				data1[i] = (unsigned char)((chgTime >> (8 * (i-2))) & 0x00ff);    
//		}
//		for(i = 4;i < 6;i++){
//				data1[i] = (unsigned char)((chgPowNormal >> (8 * (i-4))) & 0x00ff);    
//		}
//		for(i = 6;i < 8;i++){
//				data1[i] = (unsigned char)((chgEnergy >> (8 * (i-6))) & 0x00ff);    
//		}  
//    //互补验证位：	
//		for(i = 0; i < 4; i++){    
//			data1[i + 8] = ~data1[i];        
//		}  
//		// 数据属性标志位：
//		data1[12] = cardDataTypePWDSet0; 
//		data1[13] = cardDataTypePWDSet1; 
//		data1[14] = cardDataTypePWDSet2; 
//		data1[15] = cardDataTypePWDSet3; 
//		// 保存金额数据	
//		card_step = card_write_data(data1);		
//		return card_step;  
//}


// 解析卡数据：读取卡内数据并解析
void parseCardData(){
    #ifdef SYS_DEBUG
		printf(" parseCardData 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x \r\n",g_ucTempbuf[10],g_ucTempbuf[11],g_ucTempbuf[12],g_ucTempbuf[13],g_ucTempbuf[14],g_ucTempbuf[15]);
	  #endif //PCB_Debug	
	  // 充电参数设置卡判断：
	  isCardBusy = 3;
		if(g_ucTempbuf[12] == cardDataTypeChgSet0 && g_ucTempbuf[13] == cardDataTypeChgSet1 && g_ucTempbuf[14] == cardDataTypeChgSet2 && g_ucTempbuf[15] == cardDataTypeChgSet3){
				#ifdef SYS_DEBUG
				printf(" card_state_chgSet \r\n");
				#endif 
			  card_type = card_state_chgSet;   //充电设置卡      			
				//读取设置卡数据：格式 = 0-3和8-11位互补; 数据位 = 0-7
				if(!((g_ucTempbuf[0]&g_ucTempbuf[8]) || (g_ucTempbuf[1]&g_ucTempbuf[9]) || (g_ucTempbuf[2]&g_ucTempbuf[10]) || (g_ucTempbuf[3]&g_ucTempbuf[11]))){          
						//数据格式匹配正确：
						cardSetsData.charArrData[0] = g_ucTempbuf[0];
				    cardSetsData.charArrData[1] = g_ucTempbuf[1];
				    cardSetsData.charArrData[2] = g_ucTempbuf[2];
				    cardSetsData.charArrData[3] = g_ucTempbuf[3];				
				    cardSetsData.charArrData[4] = g_ucTempbuf[4];
				    cardSetsData.charArrData[5] = g_ucTempbuf[5];
				    cardSetsData.charArrData[6] = g_ucTempbuf[6];
				    cardSetsData.charArrData[7] = g_ucTempbuf[7];				      
				}
		}
		// 密码等其他数据设置卡判断：
		if(g_ucTempbuf[12] == cardDataTypePWDSet0 && g_ucTempbuf[13] == cardDataTypePWDSet1 && g_ucTempbuf[14] == cardDataTypePWDSet2 && g_ucTempbuf[15] == cardDataTypePWDSet3){
				#ifdef SYS_DEBUG
				printf(" card_state_pwdSet \r\n");
				#endif 
			  card_type = card_state_pwdSet;   //充电设置卡      			
				//读取设置卡数据：格式 = 0-3和8-11位互补;数据位 = 0-7
				if(!((g_ucTempbuf[0]&g_ucTempbuf[8]) || (g_ucTempbuf[1]&g_ucTempbuf[9]) || (g_ucTempbuf[2]&g_ucTempbuf[10]) || (g_ucTempbuf[3]&g_ucTempbuf[11]))){          
						//数据格式匹配正确：
						cardSetsData.charArrData[0] = g_ucTempbuf[0];
				    cardSetsData.charArrData[1] = g_ucTempbuf[1];
				    cardSetsData.charArrData[2] = g_ucTempbuf[2];
				    cardSetsData.charArrData[3] = g_ucTempbuf[3];				
				    cardSetsData.charArrData[4] = g_ucTempbuf[4];
				    cardSetsData.charArrData[5] = g_ucTempbuf[5];
				    cardSetsData.charArrData[6] = g_ucTempbuf[6];
				    cardSetsData.charArrData[7] = g_ucTempbuf[7];				      
				}
		}
		// 判断是否是免费卡数据：
		if(g_ucTempbuf[12] == cardDataTypeFree0 && g_ucTempbuf[13] == cardDataTypeFree1 && g_ucTempbuf[14] == cardDataTypeFree2 && g_ucTempbuf[15] == cardDataTypeFree3){				
				#ifdef SYS_DEBUG
				printf(" card_state_free \r\n");
				#endif 
			  card_type = card_state_free; //免费卡   
        // 免费卡，会员号： 0 - 7 = 会员号			
        if(!((g_ucTempbuf[0]&g_ucTempbuf[8]) || (g_ucTempbuf[1]&g_ucTempbuf[9]) || (g_ucTempbuf[2]&g_ucTempbuf[10]) || (g_ucTempbuf[3]&g_ucTempbuf[11]))){          
						//数据格式匹配正确：
						cardSetsData.charArrData[0] = g_ucTempbuf[0]; 
				    cardSetsData.charArrData[1] = g_ucTempbuf[1];  
				    cardSetsData.charArrData[2] = g_ucTempbuf[2]; 
				    cardSetsData.charArrData[3] = g_ucTempbuf[3];				
				    cardSetsData.charArrData[4] = g_ucTempbuf[4];  
				    cardSetsData.charArrData[5] = g_ucTempbuf[5]; 
				    cardSetsData.charArrData[6] = g_ucTempbuf[6]; 
				    cardSetsData.charArrData[7] = g_ucTempbuf[7];	
            #ifdef SYS_DEBUG
						printf("  card_state_free memid = %s \r\n",cardSetsData.charArrData);
						#endif 
            // 会员充电：启动充电
				    #if Non_Plug_And_Charge > 0
            startChgExternalReason.chargeControl_bit.reason_card = 1;
						main_update = 1;	
            #endif		
            #if beep_type > 0 && (Using_UART_LCD == LCD_4P3_UART || beep_type == beep_APM || beep_type == beep_BPM)
						// 读卡后，提示音
						beep_start(1,150,200);				    
						#endif				
				}	 			
		}	
		//卡内金额读取解析：金钱标志为后四位[bit12-15]，一般 = 块地址 + 块地址取反 + 块地址 + 块地址取反
		if(g_ucTempbuf[12] == cardDataTypeCash0 && g_ucTempbuf[13] == cardDataTypeCash1 && g_ucTempbuf[14] == cardDataTypeCash2 && g_ucTempbuf[15] == cardDataTypeCash3){
				unsigned char cashTipsTarget[4] = CASH_TIP;
			  unsigned char passwdCash[6]     = CASH_PWD;
				unsigned char cashTips[4]={'\0','\0','\0','\0'};
				unsigned char i = 0;				
				#ifdef SYS_DEBUG
				printf("  card_state_cash \r\n");
				#endif 
				card_type = card_state_cash;
				for(i = 0; i < 4; i++){
						cashTips[i] = g_ucTempbuf[i + 8];
				}      
				encryptStr(cashTips,passwdCash,4);
				// 金额格式：0-3和4-7互补;
				if(isSameArr(cashTips,cashTipsTarget,4)){                
						if((g_ucTempbuf[0]&g_ucTempbuf[4]) || (g_ucTempbuf[1]&g_ucTempbuf[5]) || (g_ucTempbuf[2]&g_ucTempbuf[6]) || (g_ucTempbuf[3]&g_ucTempbuf[7])){          
								//printf("  card_state_cash 222   \r\n");
						    card_step = -85;
						    cardCashData.intData = 0;
						} else {
								encryptStr(g_ucTempbuf,passwdCash,4);  
                cardCashData.arrData[3] = g_ucTempbuf[0];	   
							  cardCashData.arrData[2] = g_ucTempbuf[1];    
                cardCashData.arrData[1] = g_ucTempbuf[2];    
                cardCashData.arrData[0] = g_ucTempbuf[3];		 					
								if(cardCashData.intData > Cash_Max){
									  cardCashData.intData = 0;
									  card_step = -82; 
								}							
						}        
				} else {        
						card_step = -83; 
						cardCashData.intData = 0; 
				}  
		}else{      
				//不是金额数据：      
				card_step = -81; 
				cardCashData.intData = 0;
		}
		
}



#endif

